import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'

const instance = axios.create({
  baseURL: '/api'
})
// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    const token = store.state.user.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    let {
      data: { message, success }
    } = response
    if (success) {
      return response.data
    } else {
      Message.error(message)
      return Promise.reject(new Error(message))
    }
  },
  function (error) {
    console.dir(error)
    if (
      error.response &&
      error.response.data &&
      error.response.data.code === 10002
    ) {
      store.dispatch('user/logout')
      Message.info('登录超时，请重新登录')
      const path = window.location.href.split('#')[1]
      console.log(path)
      router.push(`/login?_topath=${path}`)
    }
    return Promise.reject(error)
  }
)
export default instance
